<template>
    <div class="app-container calendar-list-container" v-loading="loading" element-loading-text="正在导出数据">
    <!-- filter 条件查询 -->
    <div class="filter-container">
      <el-select
        v-model="listQuery.type"
        placeholder="请选择"
        style="width: 150px;margin-right:15px;"
        class="filter-item">
          <el-option
          :value="item"
          :label="item"
          v-for="(item,index) of this.workCenter"
          :key="index"/>
      </el-select>
      <el-input
            @keyup.enter.native="getData"
            clearable
            v-model="listQuery.jobNumber"
            style="width: 150px;margin-right:15px;"
            class="filter-item"
            placeholder="请输入员工工号"
      ></el-input>
      <el-input
            @keyup.enter.native="getData"
            clearable
            v-model="listQuery.name"
            style="width: 150px;margin-right:15px;"
            class="filter-item"
            placeholder="请输入员工姓名"
      ></el-input>
      <el-date-picker
        :clearable="false"
        v-model="dateMonth"
        value-format="yyyy-MM"
        format="yyyy-MM"
        type="month"
        placeholder="选择月"
        style="margin-right:15px;"
        >
      </el-date-picker>
      <el-button class="filter-item" type="primary" v-waves icon="el-icon-search" @click="getData">获取数据</el-button>
      <el-button class="filter-item" type="primary" v-waves icon="el-icon-refresh-left" :loading="updateAllStaff" @click="updateAll">刷新全部工时</el-button>
      <el-button class="filter-item" type="primary" v-waves icon="el-icon-refresh-left" :loading="updatejb" @click="updatejbfresh">刷新加班工时</el-button>
    </div>

      <el-table ref="table" :height="height" :data="tableInfo" v-loading="loadingList" element-loading-text="给我一首歌的时间" stripe border fit highlight-current-row style="width: 100%">
        <el-table-column fixed="left" label="序号" type="index" align="center" width="60"/>
        <el-table-column fixed="left" label="员工姓名"  prop="username" align="center" width="100"/>
        <el-table-column fixed="left" label="员工工号"  prop="jobNumber" align="center" width="100"/>
        <el-table-column fixed="left" label="线别"  prop="lineName" align="center" width="100"/>
        <!-- show-overflow-tooltip -->
        <el-table-column label="入职时间"  prop="entryTime" align="center" width="100"/>
        <el-table-column label="当月每日系统扫描工时(H)" align="left">
          <el-table-column  v-for="(item,index) in tableColumns" :key="index" :prop="item.prop" :label="item.label" align="center"  width="80"/>
        </el-table-column>
        <el-table-column label="应出勤" align="center">
          <el-table-column label="工时(H)" prop="YCQ" align="center" width="120"/>
        </el-table-column>
        <el-table-column label="实出勤" align="center">
          <el-table-column label="工时(H)" prop="SCQ" align="center" width="120"/>
        </el-table-column>
        <el-table-column label="加班" align="center">
          <el-table-column label="工时(H)" prop="JB" align="center" width="120"/>
        </el-table-column>
        <el-table-column label="标准" align="center">
          <el-table-column label="工时(H)" prop="BZ" align="center" width="120"/>
        </el-table-column>
        <el-table-column label="扫码" align="center">
          <el-table-column label="工时(H)" prop="CP" align="center" width="120"/>
        </el-table-column>
        <el-table-column label="异常" align="center">
          <el-table-column label="工时(H)" prop="YC" align="center" width="120"/>
        </el-table-column>
        <el-table-column label="间接" align="center">
          <el-table-column label="工时(H)" prop="JJ" align="center" width="120"/>
        </el-table-column>
        <el-table-column label="总产品" align="center">
          <el-table-column label="工时(H)" prop="ZCP" align="center" width="120"/>
        </el-table-column>
        <el-table-column label="总出勤" align="center">
          <el-table-column label="工时(H)" prop="ZCQ" align="center" width="120"/>
        </el-table-column>
        <el-table-column label="综合" align="center">
          <el-table-column label="工时A(H)" prop="ZHA" align="center" width="120"/>
        </el-table-column>
        <el-table-column label="综合" align="center">
          <el-table-column label="工时B(H)" prop="ZHB" align="center" width="120"/>
        </el-table-column>
        <el-table-column label="综合产品" align="center">
          <el-table-column label="工时(H)" prop="ZHCP" align="center" width="120"/>
        </el-table-column>
        <el-table-column label="工时" align="center">
          <el-table-column label="完成率(%)" prop="GS" align="center" width="120"/>
        </el-table-column>
        <el-table-column label="工时完成率" align="center">
          <el-table-column label="工时(%)" prop="GSWCL" align="center" width="120"/>
        </el-table-column>
        <el-table-column label="综合" align="center">
          <el-table-column label="工作效率(%)" prop="ZH" align="center" width="120"/>
        </el-table-column>
        <el-table-column label="综合工时" align="center">
          <el-table-column label="完成率(%)" prop="ZHGS" align="center" width="120"/>
        </el-table-column>
        <el-table-column fixed="right" label="操作"  align="center" width="140" v-if="userInfo.roleId == 1 || userInfo.roleId == 2 || userInfo.roleId == 0 || userInfo.roleId == 14">
          <template slot-scope="scope" >
                <el-button size="mini" type="primary" v-waves icon="el-icon-refresh-left" :loading="scope.row.updateStaff" @click="submitupdate(scope.row,scope.$index)"></el-button>
                <el-button size="mini" type="primary" @click="handleEdit(scope.row)">修改</el-button>
          </template>
        </el-table-column>
        <!-- <el-table-column fixed="right" label="当月总工时(H)"  prop="sum" align="center" width="120"/> -->
      </el-table>
      <div slot="tip" class="el-upload__tip">提示：H指的是小时</div>

   <!-- pagination 分页 -->
    <div class="pagination-container">
      <el-pagination
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="listQuery.page"
        :page-sizes="[5,10, 20, 30, 40, 100, 300, 500]"
        :page-size="listQuery.limit"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </div>

    <el-divider></el-divider>

    <el-button style="margin-right: 10px" type="success" size="small" @click="hExportExcel">导出数据Excel</el-button>

    <el-button type="success" size="small" @click="hExportDetailExcel">导出修改工时记录明细</el-button>
 
    <!-- 修改工段信息弹出表单 -->
    <el-dialog title="工时修改" :visible.sync="dialogFormVisible" width="700px">
      <el-form :model="modifyform" :rules="rules" ref="modifyform">
        <el-form-item label="工时类型" :label-width="formLabelWidth" prop="type">
          <el-select v-model="modifyform.type" placeholder="请选择工时类型" style="width:400px">
            <el-option :value="item.value" :label="item.value" v-for="(item,index) in this.typeList" :key="index"/>
          </el-select>
        </el-form-item>
        <el-form-item label="描述" :label-width="formLabelWidth" prop="content">
          <el-input clearable type="textarea" :autosize="{ minRows: 2, maxRows: 4}" v-model="modifyform.content" placeholder="请输入描述" style="width:400px" />
        </el-form-item>
        <el-form-item label="工时(H)" :label-width="formLabelWidth" prop="time">
          <el-input clearable v-model="modifyform.time" placeholder="请输入工时(H)" style="width:400px" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button :loading="modifyLoading" type="primary" @click="submitForm('modifyform')">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getInTheDayTime1,saveYCAndJJUserDatePerformance,findUserDatePerformanceInfo,updateDatamsg,updateAllDatamsg,save_zcq_jb } from '@/api/performance.js'
export default {
        name: 'workHours_Data',
        data() {
        return {
            total: 0,                           //数据的总数
            listQuery: {
                page: 1,                          //页码
                limit: 10,                        //每页显示的数据条数
                name: '',                    //员工姓名
                jobNumber: '',                    //员工工号
                type: '装配'
            },
            tableInfo: [],
            loadingList: false,
            loading:false,
            tableColumns: [],
            dateMonth: this.setMonth(),
            height: 670,
            modifyform: {
              type: '',
              time: '',
              content: ''
            },
            typeList: [
              {key: 'YC',value:'异常工时(H)'},
              {key: 'JJ',value:'间接工时(H)'},
              {key: 'BZ',value:'标准工时(H)'},
              {key: 'SCQ',value:'实出勤工时(H)'},
              {key: 'JB',value:'加班工时(H)'}
            ],
            dialogFormVisible: false,
            formLabelWidth: '100px',
            rules: {
                type: [
                  { required: true, message: '请选择工时类型', trigger: 'blur' }
                ],
                time: [
                  { required: true, message: '请输入工时(H)', trigger: 'blur' }
                ],
                content: [
                  { required: true, message: '请输入描述', trigger: 'blur' }
                ]
            },
            updaterules: {
                jobNumber: [
                  { required: true, message: '请选择工时类型', trigger: 'blur' }
                ],
                date: [
                  { required: true, message: '请输入工时(H)', trigger: 'blur' }
                ]
            },
            userInfo: this.$store.state.user.userInfo,
            updateAllStaff: false,
            updatejb: false,
            workCenter: [
              '装配',
              '数控',
              'EMS'
            ],
            modifyLoading: false
          }
    },
    watch: {
      /* 监听table数据对象 */
      tableInfo(val){
        console.log('更新table组件')
        this.doLayout();
      }
    },
    methods: {
      /* 重新渲染table组件 */
      doLayout(){
        let that = this
        this.$nextTick(() => {
          that.$refs.table.doLayout()
        })
      },
      transformDat(res) {
      const mapInfo = {
        index: '序号',
        entryTime: '入职时间',
        lineName: '线别',
        username: '员工姓名',
        jobNumber: '员工工号',
        YCQ:'应出勤',
        SCQ: '实出勤',
        JB: '加班',
        BZ: '标准',
        CP: '扫码',
        YC: '异常',
        JJ: '间接',
        ZCP: '总产品',
        ZCQ: '总出勤',
        ZHA: '综合A',
        ZHB: '综合B',
        ZHCP: '综合产品',
        GS: '工时',
        GSWCL:'工时完成率',
        ZH: '综合',
        ZHGS: '综合工时',
      }
      console.log('days',this.getDaysInMonth(this.dateMonth.split('-')[0],this.dateMonth.split('-')[1]))
      for(let i = 1;i<=this.getDaysInMonth(this.dateMonth.split('-')[0],this.dateMonth.split('-')[1]);i++){
        this.$set(mapInfo,'day'+i,'day'+i)
      }
      // 对data进行格式化
      // 取出所有的属性名，表头由接口返回的顺序决定
      const props = Object.keys(res[0]) // ['id','']
      console.log('取出英文属性名',props)
      // 将属性名从英文转为中文
      const header = props.map(zhkey => mapInfo[zhkey])
      const multiHeaderr  = header.map(item=>{
        let items = item == 'day1'?'日期':
        item.includes('day')?'':
        item.includes('综合A')?'综合':
        item.includes('综合B')?'综合':item
        return items
      })
      let multiHeader = []
      multiHeader[0] = multiHeaderr
      const multiHeaderr2  = header.map(item=>{
        let items = item.includes('day')?item:
        item.includes('应出勤')?'工时(H)':
        item.includes('实出勤')?'工时(H)':
        item.includes('加班')?'工时(H)':
        item.includes('标准')?'工时(H)':
        item.includes('扫码')?'工时(H)':
        item.includes('异常')?'工时(H)':
        item.includes('间接')?'工时(H)':
        item.includes('总产品')?'工时(H)':
        item.includes('总出勤')?'工时(H)':
        item.includes('综合A')?'工时A(H)':
        item.includes('综合B')?'工时B(H)':
        item.includes('综合产品')?'工时(H)':
        item.includes('工时')?'完成率(%)':
        item.includes('工时完成率')?'工时(%)':
        item.includes('综合')?'工作效率(%)':
        item.includes('综合工时')?'完成率(%)':''
        return items
      })
      let multiHeader2 = []
      multiHeader2[0] = multiHeaderr2
      // 进行所有表头的单元格合并
      const merges1 = [
        'A1:A2',
        'B1:B2',
        'C1:C2',
        'D1:D2',
        'E1:E2'
      ]
      const merges = this.dealMerges(merges1)
      // const data=[['xxxx','总裁办'，'13800000']]
      const data = res.map(obj => Object.values(obj))
      return { header,multiHeader,multiHeader2,merges,data }
    },
    // 导出excel
    async hExportExcel() {
      this.loading = true
      let query = Object.assign({},this.listQuery)
      query.date = this.dateMonth
      query.page = 1
      query.limit = 10000
      console.log('%c导出excel传的参数query:','color:green;font-size:16px;')
      console.log(query)

      let arr = await getInTheDayTime1(query)
      let user_nameString = this.listQuery.name?this.listQuery.name + '-':''
      let jobNumberString = this.listQuery.jobNumber?'工号' + this.listQuery.jobNumber + '-':''
      let dateString = query.date?'时间' + query.date + '-':''
      let nameString =  user_nameString + jobNumberString + dateString
      const { header,multiHeader,multiHeader2,merges, data } = this.transformDat(this.setSort(arr.data.InTheDayTime1))
      console.log(header,data)
      import('@/vendor/Export2Excel2').then(excel => {
        // excel表示导入的模块对象
        console.log(excel)
        excel.export_json_to_excel({
          multiHeader, // 表头 必填
          multiHeader2,
          data, // 具体数据 必填
          merges,
          filename: nameString + '员工工时数据' + 'excel', // 文件名称
          autoWidth: true, // 宽度是否自适应
          bookType: 'xlsx' // 生成的文件类型
        })
      })
      this.loading = false
    },
    // 排序函数
    setSort(arr){
      let newArr = JSON.parse(JSON.stringify(arr))
      let arr1 = []
      newArr.forEach((item,index)=>{
        var index2 = index
        let obj = {
          index: index+1,
          lineName: item.lineName,
          entryTime: item.entryTime,
          jobNumber: item.jobNumber,
          username: item.username
      }
      let day = 1
      Object.keys(item).forEach((items,index1)=>{
        if(items.includes('day')){
          this.$set(obj,'day'+day,newArr[index2]['day'+day])
          day++
        }
      })
      obj.YCQ = item.YCQ
      obj.SCQ = item.SCQ
      obj.JB = item.JB
      obj.BZ = item.BZ
      obj.CP = item.CP
      obj.YC = item.YC
      obj.JJ = item.JJ
      obj.ZCP = item.ZCP
      obj.ZCQ = item.ZCQ
      obj.ZHA = item.ZHA
      obj.ZHB = item.ZHB
      obj.ZHCP = item.ZHCP
      obj.GS = item.GS
      obj.GSWCL = item.GSWCL
      obj.ZH = item.ZH
      obj.ZHGS = item.ZHGS
      arr1.push(obj)
      })
      return arr1
    },
    getDaysInMonth(year,month){
        let temp = new Date(year,month,0);
        return temp.getDate();
    },
    async handleFilter(param) {
      this.loadingList = true
      let query = Object.assign({},this.listQuery)
      // 用来判断查询的条件是否为空，当不为空时，则返回到首页，也就是第一页
      if(param=='1') {
		    query.page = 1
        this.listQuery.page = 1
      } else {
        console.log('搜索内容不为空')
      }
      query.date = this.dateMonth
      let data = await getInTheDayTime1(query)
      this.loadingList = false
      if(data.code == '2') return this.$message.error(data.msg)
      console.log('data',data)
      this.total = data.data==null?0:data.data.count
      this.tableInfo = data.data.InTheDayTime1==null?[]:data.data.InTheDayTime1
      if(this.tableInfo.length<10){this.height = ''} else {this.height = 670}
      if(!this.tableInfo.length) return
      this.tableColumns = []
      for(let i = 1;i<=this.getDaysInMonth(this.dateMonth.split('-')[0],this.dateMonth.split('-')[1]);i++){
        let obj = {
            prop: 'day' + i,
            label : 'day' + i
          }
          this.tableColumns.push(obj)
      }
    },
    clearData(){
      this.listQuery.page = 1
      this.listQuery.limit = 10
    },
    getData(){
      this.clearData()
      this.handleFilter('1')
    },
    // table表单下方的页码组件改变每页显示的数据条数
     handleSizeChange(val) {
      this.listQuery.limit = val
      console.log('listQuery',val)
      if(val == 5) {
        this.height = ''
      } else {
        this.height = 670
      }
      this.handleFilter()
    },
    // table表单下方的页码组件改变页面
     handleCurrentChange(val) {
      this.listQuery.page = val
      this.handleFilter()
    },
    //初始默认执行(重点)
    getNowTime() {
      let dateTime = +new Date()+8*3600*1000
      const start = new Date(dateTime - 3600 * 1000 * 24 * 7)
        .toISOString()
        .replace('T', ' ')
        .split('.')[0] //默认开始时间7天前
      const end = new Date(dateTime)
        .toISOString()
        .replace('T', ' ')
        .split('.')[0]//默认结束时间当前时间
      console.log([start, end])
      return [start, end]
    },
    setMonth() {
        var date = new Date()
        var year = date.getFullYear()
        var month = this.filterMonth(date.getMonth()+1)
        return year + '-' + month
    },
    filterMonth(value) {
      if (value<10) {
        return '0' + value
      } else {
        return value
      }
    },
    handleEdit(item) {
      this.modifyform.date = this.dateMonth
      this.modifyform.jobNumber = item.jobNumber
      this.dialogFormVisible = true
    },
    async modifyHours(){
      this.modifyLoading = true
      let query = Object.assign({},this.modifyform)
      query.type = query.type == '异常工时(H)'?'YC':
      query.type == '间接工时(H)'?'JJ':
      query.type == '标准工时(H)'?'BZ':
      query.type == '实出勤工时(H)'?'SCQ':
      query.type == '加班工时(H)'?'JB':''
      query.landerJobNumber = this.userInfo.account
      query.landerPhone = this.userInfo.phone
      let {data,code,msg} = await saveYCAndJJUserDatePerformance(query)
      this.modifyLoading = false
      if(code == '1'){
          this.$message({
            message: '修改成功',
            type: 'success'
          })
          this.handleFilter()
          this.dialogFormVisible = false
      } else {
          this.$message({
              message: msg,
              type: 'warning'
          })
      }
    },
    // 修改异常/间接工时
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.modifyHours()
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    dealMerges(merges1){
      let days  = this.getDaysInMonth(this.dateMonth.split('-')[0],this.dateMonth.split('-')[1])
      let merges = merges1
      if(days==28){
        merges.push('F1:AG1')
        merges.push('AH1:AH1')
      } else if(days==29){
        merges.push('F1:AH1')
        merges.push('AI1:AI1')
      } else if(days==30){
        merges.push('F1:AI1')
        merges.push('AJ1:AJ1')
      } else if(days==31){
        merges.push('F1:AJ1')
        merges.push('AK1:AK1')
      }
      return merges
    },
    // 导出明细
    async hExportDetailExcel(){
      this.loading = true
      let query = {}
      query.page = 1
      query.limit = 10000
      let arr = await findUserDatePerformanceInfo(query)
      if(!arr.data.length){
        this.loading = false
        this.$message({
            message: '修改工时记录明细暂无数据',
          type: 'warning'
        })
        return
      }
      const { header, data } = this.transformDatDetail(this.setSortDetail(arr.data))
      console.log(header,data)
      import('@/vendor/Export2Excel').then(excel => {
        // excel表示导入的模块对象
        console.log(excel)
        excel.export_json_to_excel({
          header, // 表头 必填
          data, // 具体数据 必填
          filename: '修改工时记录明细' + 'excel', // 文件名称
          autoWidth: true, // 宽度是否自适应
          bookType: 'xlsx' // 生成的文件类型
        })
      })
      this.loading = false
    },
    transformDatDetail(res) {
      const mapInfo = {
        index: '序号',
        createTime: '创建时间',
        id: '记录id',
        date: '日期',
        userName: '员工姓名',
        jobNumber: '员工工号',
        landerJobNumber: '上传者账号',
        landerPhone: '上传者手机号码',
        type: '工时类型',
        time: '修改工时',
        content: '描述'
      }
      // 对data进行格式化
      // 取出所有的属性名
      const props = Object.keys(res[0]) // ['id','']
      console.log(props)
      // 将属性名从英文转为中文
      const header = props.map(zhkey => mapInfo[zhkey])
      // const data=[['xxxx','总裁办'，'13800000']]
      const data = res.map(obj => Object.values(obj))
      console.log(data)
      return { header, data }
    },
    // 导出明细，排序函数
    setSortDetail(arr){
      let newArr = JSON.parse(JSON.stringify(arr))
      let arr1 = []
      newArr.forEach((item,index)=>{
        let obj = {
          index: index+1,
          createTime: item.createTime,
          id: item.id,
          date: item.date,
          userName: item.userName,
          jobNumber: item.jobNumber,
          landerJobNumber: item.landerJobNumber,
          landerPhone: item.landerPhone,
          type: item.type=='YC'?'异常工时':
                item.type=='JJ'?'间接工时':
                item.type=='SCQ'?'实出勤工时':
                item.type=='JB'?'加班工时':
                item.type=='BZ'?'标准工时':'',
          time: item.time,
          content: item.content
      }
      arr1.push(obj)
      })
      return arr1
    },
    updateValid(form){
      this.$refs[form].validate((valid) => {
        if (valid) {
          this.submitupdate()
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    // 刷新员工工时
    async submitupdate(row,index){
      this.tableInfo[index].updateStaff = true
      let query = {
        jobNumber: row.jobNumber,
        date: this.dateMonth
      }
      let res = await updateDatamsg(query)
      if(res.code == '1'){
          this.$message({
            message: '刷新成功！',
            type: 'success'
          })
          this.handleFilter()
          this.tableInfo[index].updateStaff = false
      } else {
          this.$message({
              message: res.msg,
              type: 'warning'
          })
      }
    },
    async updateAll(){
      this.updateAllStaff = true
      let query = {
        date: this.dateMonth
      }
      let res = await updateAllDatamsg(query)
      if(res.code == '1'){
          this.$message({
            message: '刷新成功！',
            type: 'success'
          })
          this.handleFilter()
          this.updateAllStaff = false
      } else {
          this.$message({
              message: res.msg,
              type: 'warning'
          })
      }
    },
    async updatejbfresh(){
      this.updatejb = true
      let query = {
        date: this.dateMonth
      }
      let res = await save_zcq_jb(query)
      if(res.code == '1'){
          this.$message({
            message: '刷新成功！',
            type: 'success'
          })
          this.handleFilter()
          this.updatejb = false
      } else if(res.code != '500') {
          this.$message({
              message: res.msg,
              type: 'warning'
          }) 
      }
      this.updatejb = false
    },
  },
  // 进入页面获取table信息
  mounted() {
    this.handleFilter()
  },
  
  created() {
  }
}
</script>

<style>
.tpc .el-time-spinner__wrapper {
  width:100% !important;
}
.tpc .el-scrollbar:nth-of-type(2) {
  display: none !important;
}
.filter-item{
  margin-top: 6px;
}
/* 去掉日期时间选择器的清空按钮 */
.el-picker-panel__footer .el-picker-panel__link-btn.el-button--text  {
  display: none;
}

</style>